# waveplugs/gozernet.py
#
#

""" json over xmpp. """

## gozerbot imports

from gozerlib.callbacks import callbacks
from gozerlib.utils.url import posturl, getpostdata
from gozerlib.persist.persist import PlugPersist
from gozerlib.commands import cmnds
from gozerlib.utils.exception import handle_exception
from gozerlib.xmpp.bot import XMPPBot

## simplejson imports

from waveapi.simplejson import dumps

## basic imports

import socket
import re

## VARS

outxmpp = "waverelay@gozerbot.org"

state = PlugPersist('gozernet')

if not state.data:
    state.data = {}
if not state.data.has_key('relay'):
    state.data['relay'] = []
if not state.data.has_key('out'):
    state.data['out'] = [outxmpp, ]

## callbacks

outbot = XMPPBot('gozernet')

def preremote(bot, event):

    if event.channel in state.data['relay'] and not event.isremote:
        return True

def handle_doremote(bot, event):

    outbot.say(state.data['out'], event.tojson())

callbacks.add('BLIP_SUBMITTED', handle_doremote, preremote, threaded=True)

def handle_gozernet_addout(bot, event):

    global state

    if not event.rest:
        event.missing('<JID>')
        return

    if not event.rest in state.data['out']:
        state.data['out'].append(event.rest)
        state.save()

    event.done()

cmnds.add('gozernet-addout', handle_gozernet_addout, 'OPER')

def handle_gozernet_delout(bot, event):

    global state

    if not event.rest:
        event.missing('<JID>')
        return

    try:
        state.data['out'].remove(event.rest)
        state.save()
    except ValueError:
        pass

    event.done()

cmnds.add('gozernet-delout', handle_gozernet_delout, 'OPER')

def handle_gozernet_outs(bot, event):
    event.reply(state.data['out'])

cmnds.add('gozernet-outs', handle_gozernet_outs, 'OPER')

def handle_gozernet_relayon(bot, event):

    global state

    if not event.rest:
        target = event.channel
    else:
        target = event.rest

    if not target in state.data['relay']:
        state.data['relay'].append(target)
        state.save()

    event.done()

cmnds.add('gozernet-relayon', handle_gozernet_relayon, 'OPER')

def handle_gozernet_relayoff(bot, event):

    global state

    if not event.rest:
        target = event.channel
    else:
        target = event.rest

    if target in state.data['relay']:
        state.data['relay'].remove(target)
        state.save()

    event.done()

cmnds.add('gozernet-relayoff', handle_gozernet_relayoff, 'OPER')

def handle_gozernet_relaylist(bot, event):

    if not event.rest:
        target = event.channel
    else:
        target = event.rest

    event.reply("gozernet relay channels: ", state.data['relay'])

cmnds.add('gozernet-relaylist', handle_gozernet_relaylist, 'OPER')
